package com.rpframework.module.common.bottom.service.impl;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rpframework.module.common.bottom.constants.MenuConstant;
import com.rpframework.module.common.bottom.service.WeixinMenuService;
import com.rpframework.module.common.bottom.weixin.resp.Material;
import com.rpframework.module.common.bottom.weixin.util.UrlUTF8Util;
import com.rpframework.module.common.bottom.weixin.util.WeixinUtil;

/**
 * 微信菜单服务接口实现类
 * ClassName:WeixinMenuServiceImpl <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason:   TODO ADD REASON(可选). <br/>
 * Date:     2016年4月13日 下午5:59:44 <br/>
 *
 * @author  Qiu ChengBing 745656220@qq.com
 * @version 
 * @since JDK 1.7
 */
@Service
public class WeixinMenuServiceImpl implements WeixinMenuService {
	private final static Logger LOG = LoggerFactory.getLogger(MenuServiceImpl.class);

	/**
	 * 创建菜单
	 * 
	 * @param menu
	 *            菜单实例
	 * @param access_token
	 *            有效的access_token
	 * @return 0表示成功，其他值表示失败
	 */
	@Override
	public int createWeixinMenu(String menu, String accessToken) {
		int code = 201;
		if (StringUtils.isBlank(menu) || StringUtils.isBlank(accessToken)) {
			LOG.error("参数缺失+menu" + menu + ":accesstoken：" + accessToken);
			code = 610;
			return code;
		}
		// 拼装创建菜单的url
		// menu_create_url菜单创建（POST） 限100（次/天）
		String url = MenuConstant.menu_create_url.replace("ACCESS_TOKEN", accessToken);
		// 调用接口创建菜单
		JSONObject jsonObject = WeixinUtil.httpRequest(url, "POST", menu);

		if (null == jsonObject) {
			LOG.error("微信返回为空+jsonObject" + jsonObject);
		}
		code = jsonObject.getInteger("errcode");
		if (0 != jsonObject.getInteger("errcode")) {
			code = jsonObject.getInteger("errcode");
			LOG.error("创建菜单失败 errcode:{} errmsg:{}", jsonObject.getInteger("errcode"), jsonObject.getString("errmsg"));
			return code;
		}
		LOG.info("创建菜单成功！ ");
		return code;
	}

	/**
	 * 删除菜单
	 */
	@Override
	public int deleteWeixinMenu(String accessToken) {
		int code = 201;
		if (StringUtils.isBlank(accessToken)) {
			LOG.error("参数缺失  accesstoken：" + accessToken);
			code = 610;
			return code;
		}
		// 拼装删除菜单的url
		// menu_delete_url菜单创建（get） 限100（次/天）
		String url = MenuConstant.menu_delete_url.replace("ACCESS_TOKEN", accessToken);
		// 调用接口创建菜单
		JSONObject jsonObject = WeixinUtil.httpRequest(url, "GET", null);
		if (null == jsonObject) {
			LOG.error("微信返回为空+jsonObject" + jsonObject);
			return code;
		}
		code = jsonObject.getInteger("errcode");
		String errorMsg = jsonObject.getString("errmsg");
		if (0 == code) {
			LOG.error("创建删除成功 errcode:{} errmsg:{}", code, errorMsg);
			return code;
		} else {
			LOG.error("创建删除失败 errcode:{} errmsg:{}", code, errorMsg);
			return code;
		}
	}

	/**
	 * 查询菜单
	 */
	@Override
	public String selectWeixinMenu(String accessToken) {
		String result = null;
		// 拼装查询菜单的url
		String url = MenuConstant.menu_get_url.replace("ACCESS_TOKEN", accessToken);
		// 调用接口创建菜单
		JSONObject jsonObject = WeixinUtil.httpRequest(url, "GET", null);
		if (null == jsonObject) {
			LOG.error("微信返回为空+jsonObject" + jsonObject);
			return result;
		}
		result = jsonObject.toString();
		LOG.info("查询菜单成功 result:{}", result);
		return result;
	}
	
	
	/**
	 *上传图片获取url接口
	 */
	@Override
	public Material addMaterial(String accessToken,String type, String mediaFileUrl) {
		Material material=null;
		try {
				// 拼接请求地址
				String uploadMediaUrl = MenuConstant.add_material_url.replace(
						"TYPE", type).replace("ACCESS_TOKEN", accessToken);
				// 定义数据分隔符
				String boundary = "------------7da2e536604c8";

				URL uploadUrl = new URL(uploadMediaUrl);
				HttpURLConnection uploadConn = (HttpURLConnection) uploadUrl
						.openConnection();
				uploadConn.setDoOutput(true);
				uploadConn.setDoInput(true);
				uploadConn.setRequestMethod("POST");
				// 设置请求头Content-Type
				uploadConn.setRequestProperty("Content-Type",
						"multipart/form-data;boundary=" + boundary);
				// 获取媒体文件上传的输出流（往微信服务器写数据）
				OutputStream outputStream = uploadConn.getOutputStream();

				URL mediaUrl = new URL(mediaFileUrl);
				HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl
						.openConnection();
				meidaConn.setDoOutput(true);
				meidaConn.setRequestMethod("GET");

				// 从请求头中获取内容类型
				String contentType = meidaConn.getHeaderField("Content-Type");
				// 根据内容类型判断文件扩展名
				String fileExt = UrlUTF8Util.getFileExt(contentType);
				// 请求体开始
				outputStream.write(("--" + boundary + "\r\n").getBytes());
				outputStream
						.write(String
								.format("Content-Disposition: form-data; name=\"media\"; filename=\"file1%s\"\r\n",
										fileExt).getBytes());
				outputStream.write(String.format("Content-Type: %s\r\n\r\n",
						contentType).getBytes());

				// 获取媒体文件的输入流（读取文件）
				BufferedInputStream bis = new BufferedInputStream(
						meidaConn.getInputStream());
				byte[] buf = new byte[8096];
				int size = 0;
				while ((size = bis.read(buf)) != -1) {
					// 将媒体文件写到输出流（往微信服务器写数据）
					outputStream.write(buf, 0, size);
				}
				// 请求体结束
				outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes());
				outputStream.close();
				bis.close();
				meidaConn.disconnect();

				// 获取媒体文件上传的输入流（从微信服务器读数据）
				InputStream inputStream = uploadConn.getInputStream();
				InputStreamReader inputStreamReader = new InputStreamReader(
						inputStream, "utf-8");
				BufferedReader bufferedReader = new BufferedReader(
						inputStreamReader);
				StringBuffer buffer = new StringBuffer();
				String str = null;
				while ((str = bufferedReader.readLine()) != null) {
					buffer.append(str);
				}
				bufferedReader.close();
				inputStreamReader.close();
				// 释放资源
				inputStream.close();
				inputStream = null;
				uploadConn.disconnect();

				// 使用JSON-lib解析返回结果
				JSONObject jsonObject = JSON.parseObject(buffer.toString());
				if (null == jsonObject) {
					 return null;
				}
				material=new Material();
				material.setMediaId(jsonObject.getString("media_id"));
				material.setUrl(jsonObject.getString("url"));
				return material;
		} catch (Exception e) {
			LOG.error("上传永久媒体文件失败：{}", e);
			return null;
		}
	}
	
	
	/**
	 * 上传永久图文素材
	 */
	@Override
	public String addnews(String accessToken,String jsonString) {
		String mediaId=null;
		// 拼接请求地址
		String url=MenuConstant.add_news_url.replace("ACCESS_TOKEN", accessToken);
		JSONObject jsonObject = WeixinUtil.httpRequest(url, "POST", jsonString);
			if (null != jsonObject) {
				mediaId=jsonObject.getString("media_id");
	             if (StringUtils.isBlank(mediaId)) {
	            	 String errmsg= jsonObject.getString("errmsg");
	                  LOG.error("上传图文错误errmsg{}",errmsg);
	                  return null;
	             	}
	             }
		return mediaId;
	}

	@Override
	public boolean deletenews(String accessToken, String mediaId) {
		String url=MenuConstant.del_material_url.replace("ACCESS_TOKEN", accessToken);
		JSONObject jsonObject = WeixinUtil.httpRequest(url, "POST", mediaId);
		if (null != jsonObject) {
			String errcode=jsonObject.getString("errcode");
			if(StringUtils.isNotBlank(errcode)&&"0".equals(errcode)){
				return true;
			}
           }
		return false;
		
	}
	
	/**
	 * 获取永久素材
	 * @param accessToken
	 * @param mediaId
	 * @return
	 */
	@Override
	public JSONObject getMaterial(String accessToken, String mediaId) {
		String url=MenuConstant.get_material_url.replace("ACCESS_TOKEN", accessToken);
		JSONObject jsonObject = WeixinUtil.httpRequest(url, "POST", mediaId);
		if (null != jsonObject) {
			String errcode=jsonObject.getString("errcode");
			if(StringUtils.isNotBlank(errcode)){
				return null;
			}
           }
		return jsonObject;
		
	}
	
	@Override
	public boolean updatenews(String accessToken, String mediaId) {
		String url=MenuConstant.update_news_url.replace("ACCESS_TOKEN", accessToken);
		JSONObject jsonObject =WeixinUtil.httpRequest(url, "POST", mediaId);
		if(null!=jsonObject){
			String errcode = jsonObject.getString("errcode");
			if(StringUtils.isNotBlank(errcode)&&"0".equals(errcode)){
				return true;
			}
		}
		return false;
	}
}
